#!/bin/bash
###
# @Author: Loganli
# @Date: 2025-05-08
# @Description: Loki简单部署脚本
###

# 创建工作目录
sudo mkdir -p /app/loki/config
sudo mkdir -p /app/loki/data
sudo chmod -R 777 /app/loki

# 创建S3配置文件
cat > /app/loki/config/loki-config.yaml << EOF
auth_enabled: false
chunk_store_config:
  max_look_back_period: 720h
compactor:
  shared_store: filesystem
  working_directory: /tmp/loki/boltdb-shipper-compactor
ingester:
  chunk_block_size: 262144
  chunk_idle_period: 3m
  chunk_retain_period: 1m
  lifecycler:
    ring:
      replication_factor: 1
  max_transfer_retries: 0
  wal:
    dir: /tmp/loki/wal
limits_config:
  enforce_metric_name: false
  max_entries_limit_per_query: 5000
  max_query_parallelism: 2
  max_query_series: 100000
  reject_old_samples: true
  reject_old_samples_max_age: 168h
  retention_period: 336h
  volume_enabled: true
memberlist:
  join_members:
  - 'loki-memberlist'
schema_config:
  configs:
  - from: "2020-10-24"
    index:
      period: 24h
      prefix: index_
    object_store: s3
    schema: v11
    store: boltdb-shipper
server:
  grpc_listen_port: 9095
  http_listen_port: 3100
    
storage_config:
  aws:
    bucketnames: pro-astralx-log
    insecure: false
    region: ap-northeast-1
    s3: s3://ap-northeast-1/pro-astralx-log
    s3forcepathstyle: true
    sse_encryption: false
  boltdb_shipper:
    active_index_directory: /tmp/loki/boltdb-shipper-active
    cache_location: /tmp/loki/boltdb-shipper-cache
    cache_ttl: 24h
    shared_store: s3
  filesystem:
    directory: /tmp/loki/chunks
table_manager:
  retention_deletes_enabled: true
  retention_period: 720h
EOF

# 运行Loki容器
docker run -d \
    --restart=always \
    -v /app/loki/config:/mnt/config \
    -v /app/loki/data:/tmp/loki \
    -p 3100:3100 \
    --log-opt max-size=1g \
    --log-opt max-file=2 \
    -e AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:-your-access-key-id} \
    -e AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY:-your-secret-access-key} \
    --name=loki \
    grafana/loki:2.8.11 -config.file=/mnt/config/loki-config.yaml

# 检查Loki是否正常运行
echo "等待Loki启动..."
sleep 5
if docker ps | grep loki > /dev/null; then
    echo "Loki已成功启动！"
    echo "Loki API地址: http://$(hostname -I | awk '{print $1}'):3100"
    echo "可以通过以下命令查看日志："
    echo "docker logs loki"
else
    echo "Loki启动失败，请检查日志："
    echo "docker logs loki"
fi
